package binarytree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 9:41
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
 * 给你二叉树的根节点 root ，返回其节点值 自底向上的层序遍历 。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）
 */
public class LevelOrderBottom {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<TreeNode> levelNodes = new LinkedList<>();
        if (root != null) {
            levelNodes.offer(root);
        }
        while (!levelNodes.isEmpty()) {
            List<Integer> temp = new ArrayList<>();
            int size = levelNodes.size();
            while (size > 0) {
                TreeNode poll = levelNodes.poll();
                temp.add(poll.val);
                size--;
                if (poll.left != null) {
                    levelNodes.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNodes.offer(poll.right);
                }
            }
            result.add(0, temp);
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
